/*
 * @Author: 谢陈洁
 * @Date: 2025-07-07 18:21:50
 * @LastEditors: 谢陈洁
 * @LastEditTime: 2025-07-23 14:36:50
 * @Description: file content
 */
import { defineStore } from 'pinia'
import { useDark, usePreferredDark } from '@vueuse/core'

// 扩展类型定义
interface ThemeState {
  mode: 'light' | 'dark' | 'system'
  color: string // 主题颜色
}

export const useThemeStore = defineStore('theme', () => {
  // 响应式状态
  const mode = ref<ThemeState['mode']>('light')
  const color = ref('#409EFF')

  // 使用VueUse的暗黑模式工具
  const isDark = useDark({
    storageKey: 'theme-mode', // 本地存储键名
    selector: 'html', // 应用类名的元素
    valueDark: 'dark', // 暗黑模式类名
    valueLight: '' // 亮色模式不添加类名
  })
  const preferredDark = usePreferredDark() // 系统偏好暗黑模式

  // 同步主题模式
  const syncThemeMode = () => {
    switch (mode.value) {
      case 'light':
        isDark.value = false
        break
      case 'dark':
        isDark.value = true
        break
      case 'system':
        isDark.value = preferredDark.value
        break
    }
  }

  // 监听模式变化自动同步
  watch([mode, preferredDark], syncThemeMode, { immediate: true })

  // 设置主题模式
  const setThemeMode = (newMode: ThemeState['mode']) => {
    mode.value = newMode
  }

  // 设置主题颜色
  const setThemeColor = (newColor: string) => {
    color.value = newColor
    document.documentElement.style.setProperty('--el-color-primary', newColor)
  }
  // 监听颜色变化
  watch(color, setThemeColor, { immediate: true })

  return {
    mode,
    color,
    isDark,
    setThemeMode,
    setThemeColor
  }
}, {
  persist: {
    key: 'theme',
    storage: localStorage,
    // paths: ['mode', 'color'] // 只持久化模式和颜色配置
  }
})
